<template>
	<view class="appointment-container">
		<!-- 毛玻璃标题栏 -->
		<view class="glass-header">
			<text class="header-title">我的预约</text>
			<view class="header-subtitle">一对一辅导管理</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-box">
				<uni-icons type="search" size="18" color="#999"></uni-icons>
				<input 
					class="search-input" 
					placeholder="搜索学生姓名" 
					v-model="searchText"
					@confirm="handleSearch"
					@input="handleInput"
					focus
				/>
				<uni-icons 
					v-if="searchText" 
					type="clear" 
					size="18" 
					color="#999"
					@click="clearSearch"
				></uni-icons>
			</view>
			<!-- 搜索历史 -->
			<!-- 搜索历史 -->
			<!-- 修改搜索历史部分的代码 -->
			<scroll-view class="search-history" scroll-x v-if="searchHistory.length > 0">
			  <view 
			    class="history-tag" 
			    v-for="(item, index) in searchHistory" 
			    :key="index"
			    @click="selectHistory(item)"
			  >
			    {{item}}
			    <view class="delete-icon" @click.stop="removeHistory(index)">
			      <uni-icons type="close" size="14" color="#999"></uni-icons>
			    </view>
			  </view>
			</scroll-view>
		</view>

		<!-- 毛玻璃状态选项卡 -->
		<view class="glass-tabs">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
				:class="{active: activeTab === index, 'has-badge': tab.count > 0}" @click="switchTab(index)">
				<text>{{tab.name}}</text>
				<view class="tab-badge" v-if="tab.count > 0">{{tab.count}}</view>
			</view>
		</view>

		<!-- 内容区域 -->
		<scroll-view class="content-scroll" scroll-y @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<!-- 骨架屏加载动画 -->
			<view class="skeleton-container" v-if="loading">
				<view class="glass-skeleton" v-for="i in 3" :key="i">
					<view class="skeleton-avatar"></view>
					<view class="skeleton-line"></view>
					<view class="skeleton-line short"></view>
					<view class="skeleton-line"></view>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-else-if="filteredAppointments.length === 0">
				<loading1></loading1>
				<text class="empty-text">{{tabs[activeTab].emptyText}}</text>
			</view>

			<!-- 预约卡片列表 -->
			<view class="appointment-list" v-else>
				<view class="glass-card" v-for="(item, index) in filteredAppointments" :key="item.id"
					@click="viewDetail(item)" :class="['animate__animated', 'animate__fadeInUp', `delay-${index%5}`]">

					<view class="card-header">
						<view class="student-info">
							<view class="student-meta">
								<text class="student-name">{{item.studentName}}</text>
								<text class="student-grade">{{item.studentGrade}}</text>
							</view>
						</view>
						<view class="status-tag" :class="getStatusClass(item.isFinish)">
							{{getStatusText(item.isFinish)}}
						</view>
					</view>

					<view class="card-content">
						<view class="info-item">
							<uni-icons type="calendar" size="18" color="#666"></uni-icons>
							<text class="info-text">预约时间：{{item.appointmentTime}}</text>
						</view>
						<view class="info-item">
							<uni-icons type="chat" size="18" color="#666"></uni-icons>
							<text class="info-text">预约内容：{{item.appointmentContent}}</text>
						</view>
						<view class="info-item" v-if="item.teacherComponent">
							<uni-icons type="compose" size="18" color="#666"></uni-icons>
							<text class="info-text">我的评价: {{item.teacherComponent}}</text>
						</view>
						<view class="info-item" v-if="item.component!=null">
							<uni-icons type="compose" size="18" color="#666"></uni-icons>
							<text class="info-text">家长评价: {{item.component}}</text>
						</view>
					</view>

					<view class="card-footer">
						<text class="price">收入：¥{{item.money}}</text>
					</view>

					<!-- 卡片装饰元素 -->
					<view class="card-decoration"></view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				teacher: {},
				activeTab: 0,
				refreshing: false,
				loading: true,
				avatarCache: {},
				appointments: [],
				searchText: '',
				searchHistory: [],
				tabs: [{
						name: '全部',
						status: -1, // -1表示全部
						count: 0,
						emptyText: '暂无预约记录'
					},
					{
						name: '待辅导',
						status: 0,
						count: 0,
						emptyText: '暂无待辅导预约'
					},
					{
						name: '待审核',
						status: 1,
						count: 0,
						emptyText: '暂无待审核预约'
					},
					{
						name: '已完成',
						status: 2,
						count: 0,
						emptyText: '暂无已完成预约'
					}
				]
			}
		},
		computed: {
			filteredAppointments() {
				let filtered = this.appointments;
				
				// 根据搜索文本筛选
				if (this.searchText) {
					const searchTextLower = this.searchText.toLowerCase();
					filtered = filtered.filter(item => 
						item.studentName && item.studentName.toLowerCase().includes(searchTextLower)
					);
				}
				
				// 根据标签筛选
				if (this.tabs[this.activeTab].status !== -1) {
					filtered = filtered.filter(item => item.isFinish === this.tabs[this.activeTab].status);
				}
				
				// 按预约时间排序（只比较年月日部分）
				return filtered.sort((a, b) => {
					// 提取年月日部分（格式：2025-08-06）
					const dateA = a.appointmentTime.split(' ')[0];
					const dateB = b.appointmentTime.split(' ')[0];
					
					// 转换为Date对象比较
					return new Date(dateB) - new Date(dateA);
				});
			}
		},
		watch: {
			filteredAppointments() {
				this.updateTabCounts();
			}
		},
		onLoad() {
			this.loadTeacherInfo();
			this.fetchAppointments();
			this.loadSearchHistory();
		},
		onShow() {
			this.fetchAppointments();
		},
		methods: {
			loadTeacherInfo() {
				uni.getStorage({
					key: "teacher",
					success: (res) => {
						this.teacher = res.data;
					}
				});
			},
			
			// 加载搜索历史
			loadSearchHistory() {
				uni.getStorage({
					key: 'appointmentSearchHistory',
					success: (res) => {
						this.searchHistory = res.data || [];
					}
				});
			},
			
			// 保存搜索历史
			saveSearchHistory() {
				if (!this.searchText.trim()) return;
				
				// 去重
				const index = this.searchHistory.indexOf(this.searchText);
				if (index !== -1) {
					this.searchHistory.splice(index, 1);
				}
				
				// 添加到数组开头
				this.searchHistory.unshift(this.searchText);
				
				// 限制最多保存10条
				if (this.searchHistory.length > 10) {
					this.searchHistory = this.searchHistory.slice(0, 10);
				}
				
				// 保存到本地
				uni.setStorage({
					key: 'appointmentSearchHistory',
					data: this.searchHistory
				});
			},
			
			// 处理搜索
			handleSearch() {
				if (this.searchText.trim()) {
					this.saveSearchHistory();
				}
				this.updateTabCounts();
			},
			
			// 输入处理
			handleInput() {
				this.updateTabCounts();
			},
			
			// 清除搜索
			clearSearch() {
				this.searchText = '';
				this.updateTabCounts();
			},
			
			// 选择历史记录
			selectHistory(item) {
				this.searchText = item;
				this.handleSearch();
			},
			
			// 修改删除历史记录的方法
			removeHistory(index) {
			  this.searchHistory.splice(index, 1);
			  uni.setStorage({
			    key: 'appointmentSearchHistory',
			    data: this.searchHistory
			  });
			},

			fetchAppointments() {
				this.loading = true;
				uni.request({
					url: `${globalVariable}/getAppointmentByTeacherId?teacherId=${this.teacher.teacherId}`,
					success: (res) => {
						if (res.data.status === 1) {
							this.appointments = res.data.data;
							this.updateTabCounts();
							this.preloadAvatars();
						}
					},
					complete: () => {
						this.loading = false;
						this.refreshing = false;
					}
				});
			},

			updateTabCounts() {
				let filtered = this.appointments;
				
				// 根据搜索文本筛选
				if (this.searchText) {
					const searchTextLower = this.searchText.toLowerCase();
					filtered = filtered.filter(item => 
						item.studentName && item.studentName.toLowerCase().includes(searchTextLower)
					);
				}
				
				this.tabs.forEach(tab => {
					if (tab.status === -1) {
						// 全部标签显示总数
						tab.count = filtered.length;
					} else {
						tab.count = filtered.filter(item => item.isFinish === tab.status).length;
					}
				});
			},

			onRefresh() {
				this.refreshing = true;
				this.fetchAppointments();
			},
			
			loadMore() {
				// 这里可以添加加载更多数据的逻辑
				console.log('加载更多数据');
			},

			switchTab(index) {
				this.activeTab = index;
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},

			viewDetail(item) {
				uni.navigateTo({
					url: `/pages/appointmentDetail/appointmentDetail?detail=` + JSON.stringify(item)
				});
			},

			getStatusClass(status) {
				return {
					0: 'status-pending',
					1: 'status-review',
					2: 'status-completed'
				} [status] || '';
			},

			getStatusText(status) {
				return {
					0: '待辅导',
					1: '待审核',
					2: '已完成'
				} [status] || '';
			},

			getAvatar(studentPhone) {
				if (this.avatarCache[studentPhone]) {
					return this.avatarCache[studentPhone];
				}
				return '/static/aver.jpg';
			},

			async checkAvatarExists(studentPhone) {
				return
			},

			handleAvatarError(studentPhone) {
				console.log("错误")
				this.$set(this.avatarCache, studentPhone, '/static/aver.jpg');
			},

			async preloadAvatars() {
				const uniquePhones = [...new Set(this.appointments.map(item => item.studentPhone))];
				await Promise.all(uniquePhones.map(phone => this.checkAvatarExists(phone)));
			},
			
			formatTime(timeStr) {
				return timeStr
			}
		}
	}
</script>

<style scoped>
	/* 基础样式 */
	.appointment-container {
		padding: 30rpx;
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 79, 10, 0.1) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(38, 10, 255, 0.1) 0%, transparent 20%);
	}

	/* 搜索容器 */
	.search-container {
		margin-bottom: 20rpx;
		position: relative;
	}

	/* 搜索框 */
	.search-box {
		display: flex;
		align-items: center;
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 20rpx 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		margin-left: 12rpx;
		margin-right: 12rpx;
	}

	/* 搜索历史 */
	.search-history {
		display: flex;
		white-space: nowrap;
		margin-top: 16rpx;
		padding: 10rpx 0;
	}

	.history-tag {
		display: inline-flex;
		align-items: center;
		background: rgba(255, 255, 255, 0.3);
		border-radius: 32rpx;
		padding: 8rpx 20rpx;
		margin-right: 16rpx;
		font-size: 24rpx;
		color: #666;
	}

	.history-tag:active {
		background: rgba(255, 255, 255, 0.5);
	}

	/* 毛玻璃标题栏 */
	.glass-header {
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
	}

	.header-title {
		font-size: 42rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.header-subtitle {
		font-size: 26rpx;
		color: #666;
	}

	/* 毛玻璃状态选项卡 */
	.glass-tabs {
		display: flex;
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		margin-bottom: 30rpx;
		padding: 10rpx;
		position: relative;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
		position: relative;
		border-radius: 16rpx;
		transition: all 0.3s ease;
	}

	.tab-item.active {
		background: rgba(255, 255, 255, 0.4);
		color: #333;
		font-weight: 500;
	}

	.tab-badge {
		position: absolute;
		top: 8rpx;
		right: 30rpx;
		background-color: #ff4d4f;
		color: white;
		font-size: 20rpx;
		min-width: 32rpx;
		height: 32rpx;
		line-height: 32rpx;
		border-radius: 16rpx;
		padding: 0 8rpx;
		transform: scale(0.8);
	}

	/* 内容区域 */
	.content-scroll {
		height: calc(100vh - 380rpx);
	}

	/* 骨架屏 */
	.skeleton-container {
		padding: 10rpx;
	}

	.glass-skeleton {
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
	}

	.skeleton-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.08);
		margin-bottom: 20rpx;
	}

	.skeleton-line {
		height: 30rpx;
		background: rgba(0, 0, 0, 0.08);
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.skeleton-line.short {
		width: 60%;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		margin: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
	}

	.empty-text {
		font-size: 28rpx;
		color: #666;
	}

	/* 毛玻璃卡片 */
	.appointment-list {
		padding-bottom: 40rpx;
	}

	.glass-card {
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		position: relative;
		overflow: hidden;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.glass-card:active {
		transform: scale(0.98);
		background: rgba(255, 255, 255, 0.3);
	}

	/* 卡片装饰元素 */
	.card-decoration {
		position: absolute;
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.15);
		top: -40rpx;
		right: -40rpx;
	}

	/* 卡片头部 */
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.student-info {
		display: flex;
		align-items: center;
	}

	.student-meta {
		display: flex;
		flex-direction: column;
	}

	.student-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 6rpx;
	}

	.student-grade {
		font-size: 24rpx;
		color: #666;
	}

	/* 状态标签 */
	.status-tag {
		font-size: 24rpx;
		padding: 6rpx 20rpx;
		border-radius: 20rpx;
		color: white;
		font-weight: 500;
	}

	.status-pending {
		background: rgba(255, 169, 64, 0.9);
	}

	.status-review {
		background: rgba(24, 144, 255, 0.9);
	}

	.status-completed {
		background: rgba(82, 196, 26, 0.9);
	}

	/* 卡片内容 */
	.card-content {
		margin-bottom: 24rpx;
	}

	.info-item {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.info-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 12rpx;
	}

	/* 卡片底部 */
	.card-footer {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding-top: 16rpx;
		border-top: 1rpx dashed rgba(0, 0, 0, 0.1);
	}

	.price {
		font-size: 28rpx;
		color: #ff4d4f;
		font-weight: 500;
	}

	/* 动画效果 */
	.animate__animated {
		animation-duration: 0.5s;
	}

	.delay-0 {
		animation-delay: 0.05s;
	}

	.delay-1 {
		animation-delay: 0.1s;
	}

	.delay-2 {
		animation-delay: 0.15s;
	}

	.delay-3 {
		animation-delay: 0.2s;
	}

	.delay-4 {
		animation-delay: 0.25s;
	}
</style>